import {
  createRouter,
  createWebHashHistory,
  createWebHistory,
} from "vue-router";

// import Home from "../pages/Home.vue";
// import About from "../pages/About.vue";

// 配置映射关系
const routes = [
  { path: "/", redirect: "home" },
  {
    path: "/home",
    name: "home",
    meta: {
      name: "pengfan",
      age: 18,
      height: 1.88,
    },
    component: () =>
      import(/* webpackChunkName: "home-chunk" */ "../pages/Home.vue"),
    children: [
      {
        path: "",
        redirect: "/home/message",
      },
      {
        path: "message",
        component: () => import("../pages/HomeMessage.vue"),
      },
      {
        path: "shops",
        component: () => import("../pages/HomeShops.vue"),
      },
    ],
  },
  {
    path: "/about",
    name: "about",
    component: () => import("../pages/About.vue"),
  },
  {
    path: "/user/:username/id/:id",
    name: "user",
    component: () => import("../pages/User.vue"),
  },
  {
    path: "/login",
    name: "login",
    component: () => import("../pages/Login.vue"),
  },
  {
    path: "/:pathMatch(.*)",
    component: () => import("../pages/NotFound.vue"),
  },
];

// 创建一个路由对象router
const router = createRouter({
  routes,
  history: createWebHashHistory(),
});

// 动态添加路由
const categoryRoute = {
  path: "/category",
  component: () => import("../pages/Category.vue"),
};

router.addRoute(categoryRoute);

// 添加二级路由对象
router.addRoute("home", {
  path: "moment",
  component: () => import("../pages/HomeMoment.vue"),
});

// 导航守卫
let counter = 0;

router.beforeEach((to, from) => {
  console.log(`进行了${++counter}路由的跳转`);
  console.log(to.path);
  // if (to.path.indexOf("/home") !== -1) {
  //   console.log(to.path.indexOf("/home"))
  //   return "/login";
  // }

  if (to.path !== "/login") {
    const token = window.localStorage.getItem("token");
    if (!token) {
      return "/login";
    }
  }
});

export default router;
